using System;
using UnityEditor;
using UnityEngine;
using PathX;
using FPLibrary;

#if UNITY_EDITOR
namespace PathX.Editor
{
    [CustomEditor(typeof(PathFindingTest))]
    public class PathFindingTestEditor : UnityEditor.Editor , INeedPath
    {
        private SerializedProperty _starTrans;
        private SerializedProperty _endTrans;
        private SerializedProperty _midTrans;

        private SerializedProperty _wayPointObj;
        private SerializedProperty _pathUnit;

        private void OnEnable()
        {
            _starTrans = serializedObject.FindProperty("startTrans");
            _endTrans = serializedObject.FindProperty("endTrans");
            _midTrans = serializedObject.FindProperty("midTrans");
            _wayPointObj = serializedObject.FindProperty("wayPointObj");
            _pathUnit = serializedObject.FindProperty("pathUnit");
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();


            if (GUILayout.Button(new GUIContent("FindPath", "找可走路径")))
            {
                BasicPathRequest pr = new BasicPathRequest();
                pr.requesterProperties = (UnitEntity)_pathUnit.objectReferenceValue;
                pr.pathFinderOptions =  (UnitEntity)_pathUnit.objectReferenceValue;
                pr.from = FPVector.ToFPVector(((Transform)_starTrans.objectReferenceValue).position);
                pr.to = FPVector.ToFPVector(((Transform)_endTrans.objectReferenceValue).position);
                pr.via = new FPVector[] {FPVector.ToFPVector(((Transform) _midTrans.objectReferenceValue).position)};
                pr.requester = this;
                
                lastFrameCount = Time.frameCount;
                
                PathServer.Instance.FindPath(pr);
            }


        }
        int lastFrameCount;
        public void ConsumePathResult(PathResult result)
        {
            Debug.Log($"pathresult = {result.status}, totalframecount = {Time.frameCount - lastFrameCount}");

            if (result.status == PathingStatus.Failed)
            {
                Debug.LogError($"path finding failed, error message = {result.errorInfo}");
                return;
            }

            if (result.status == PathingStatus.Complete)
            {
                ((PathFindingTest) target).pathResult = result;
                var wayPointGo = (GameObject) _wayPointObj.objectReferenceValue;
                var len = result.path.count;
                for(int i = 0;i<len;i++)
                {
                    var pos = result.path.PeekFront(i);
                    Debug.Log($"pos {i} - {pos.position}");
                    var r = GameObject.Instantiate(wayPointGo);
                    r.transform.position = pos.position.ToVector();
                }
                Debug.Log($"path founded,Length = {len}");
            }
        }
    }
}
#endif